namespace AspNet.Identity.Manager.Migrations
{
    using AspNet.Identity.Manager;
    using AspNet.Identity.Manager.Models;
    using Microsoft.AspNet.Identity;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<AspNet.Identity.Manager.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            ContextKey = "AspNet.Identity.Manager.Models.ApplicationDbContext";
        }

        protected override void Seed(ApplicationDbContext context)
        {
            if (context.Roles.Count(r => r.Name == AspNet.Identity.Manager.Constants.AdministratorRole) == 0)
            {
                // Add role Administrator.
                ApplicationRole adminRole = new ApplicationRole() { Name = AspNet.Identity.Manager.Constants.AdministratorRole };
                context.Roles.Add(adminRole);
            }

            string administratorId = context.Roles.FirstOrDefault(r => r.Name == AspNet.Identity.Manager.Constants.AdministratorRole).Id;

            ApplicationUser user = context.Users.FirstOrDefault(u => u.Roles.Count(r => r.RoleId == administratorId) == 1);

            if (user == null)
            {
                // if not exists a administrator, then add.
                UserManager userManager = new UserManager();
                user = userManager.FindByName("admin");
                IdentityResult userResult = null;

                if (user == null)
                {
                    user = new ApplicationUser("admin");
                    userResult = userManager.Create(user, "Pa$$word123+");
                }

                if (userResult == null || userResult.Succeeded)
                {
                    userManager.AddToRole(user.Id, AspNet.Identity.Manager.Constants.AdministratorRole);
                }
            }
        }
    }
}
